<template>
	<view class="equipment-manage">
		<gyd-navbar back-color="#fff" :title="title"></gyd-navbar>

		<view class="content">
			<view class="statistics-card">
				<view class="grid-item">
					<text class="label">总数</text>
					<text class="value">{{dataInfo.total}}</text>
				</view>
				<view class="grid-item" :class="params.current==0?'active':''" @click="changeTab(0)">
					<text class="label">未划拨</text>
					<text class="value">{{dataInfo.unallocated_num}}</text>
				</view>
				<view class="grid-item" :class="params.current==1?'active':''" @click="changeTab(1)">
					<text class="label">已划拨</text>
					<text class="value">{{dataInfo.allocated_num}}</text>
				</view>
				<view class="grid-item" :class="params.current==2?'active':''" @click="changeTab(2)">
					<text class="label">已安装</text>
					<text class="value">{{dataInfo.installed_num}}</text>
				</view>
				<view class="grid-item" :class="params.current==3?'active':''" @click="changeTab(3)">
					<text class="label">未安装</text>
					<text class="value">{{dataInfo.notinstalled_num}}</text>
				</view>
			</view>

			<!--筛选-->
			<view class="filter-box">
				<view class="filter-item">
					<uni-data-select v-model="params.device_type" :localdata="deviceTypeList" @change="changeDeviceType"
						placeholder="设备类型"></uni-data-select>
				</view>
				<view class="filter-item">
					<uni-data-select v-model="params.device_model" :localdata="deviceModelList"
						@change="changeDeviceModel" placeholder="设备型号"></uni-data-select>
				</view>
				<view class="filter-item" v-if="params.current==1 || params.current==2">
					<uni-data-select v-model="params.holder_type" :localdata="holderTypeList" @change="changeHolderType"
						placeholder="持有人类型"></uni-data-select>
				</view>
				<view class="filter-item" v-if="params.current==2 || params.current==3">
					<uni-data-select v-model="params.sales_method" :localdata="salesMethodList"
						@change="changeSalesMethod" placeholder="销售方式"></uni-data-select>
				</view>
				<view class="filter-item" v-if="params.current==0">
					<u-button type="primary" size="small" plain @click="batchOperation">批量操作</u-button>
				</view>
				<!-- <view class="filter-item">
					<uni-data-select v-model="params.ad_position" :localdata="adPositionList" @change="changeAdPosition"
						placeholder="广告位置"></uni-data-select>
				</view> -->
			</view>
			<!-- <view class="filter-box">
				<view class="area-opt">
					<uni-data-select class="area-item" v-model="params.province" :localdata="provinceList"
						@change="getCity" placeholder="省查询"></uni-data-select>
					<uni-data-select class="area-item" v-model="params.city" :localdata="cityList" @change="getArea"
						placeholder="市查询"></uni-data-select>
					<uni-data-select class="area-item" v-model="params.area" :localdata="areaList" @change="getDataList"
						placeholder="区县查询"></uni-data-select>
				</view>
			</view> -->
			<u-checkbox-group v-model="selectIds" @change="checkboxChange">
				<view class="device-card" v-for="(item,index) in list" :key="index">
					<view class="device-info">
						<view class="checkbox" v-if="operate">
							<u-checkbox :key="index" :name="item.id"></u-checkbox>
						</view>
						<view class="info-left">
							<view class="value">{{item.device_type_str}}<text>{{item.name}}</text></view>
							<view class="value">编号：{{item.device_no}}</view>
							<view class="value">
								基础价：{{item.rent}}
								<text>加价：{{item.additional_amount}}</text>
								<text>合计：{{item.amount}}</text>
							</view>
						</view>
						<view class="info-right">
							<template v-if="params.current==0">
								<view class="btn-group">
									<u-button class="btn" type="primary" size="mini" plain
										@click="allocate(item)">划拨</u-button>
									<u-button class="btn" type="primary" size="mini" plain
										@click="adjustment(item)">改价</u-button>
								</view>
							</template>
						</view>
					</view>
				</view>
			</u-checkbox-group>

			<view class="device-card" style="text-align: center;" v-if="list.length===0">暂无数据</view>
		</view>

		<template v-if="operate">
			<view class="footer">
				<view class="btn-group">
					<u-button class="btn" type="primary" size="normal" @click="batchAllocate()">批量划拨</u-button>
					<u-button class="btn" type="primary" size="normal" @click="batchAdjustment()">批量改价</u-button>
				</view>
			</view>
		</template>

		<!-- 划拨弹窗 -->
		<allocate-view ref="allocateRef" :data="selectIds"></allocate-view>

		<!-- 改价弹窗 -->
		<price-adjustment ref="adjustmentRef" :data="selectIds"></price-adjustment>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';
	import allocateView from './components/allocate-view/allocate-view.vue';
	import priceAdjustment from './components/price-adjustment/price-adjustment.vue';

	const state = reactive({
		title: '运营中心设备管理',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		dataInfo: {
			total: 0,
			unallocated_num: 0,
			allocated_num: 0,
			installed_num: 0,
			notinstalled_num: 0,
		},
		params: {
			current: 0,
			device_type: 0,
			device_model: 0,
			holder_type: 0,
			sales_method: 0,
			province: 0,
			city: 0,
			area: 0,
		},
		isMore: true,
		list: [],
		operate: false,
		selectIds: [],
	});

	const deviceTypeList = ref([]);
	const deviceModelList = ref([]);
	const holderTypeList = ref([]);
	const salesMethodList = ref([]);
	const provinceList = ref([]);
	const cityList = ref([]);
	const areaList = ref([]);

	const allocateRef = ref(null);
	const adjustmentRef = ref(null);

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		initData();
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
		search();
	})

	onReachBottom(() => {
		console.log('触底加载更多');
		getDataList();
	})

	function initData() {
		getData();
		getDataList();
		getSearchCriteria();
		getProvince();
	}

	function getData() {
		request.get("agent.equipment/index", state.params).then(res => {
			console.log('数据', res);
			state.dataInfo = res.data;
		})
	}

	function getDataList() {
		if (!state.isMore) {
			util.showTip('没有更多了');
			return;
		}
		state.params.skip = state.list.length;
		request.get("agent.equipment/list", state.params).then(res => {
			console.log('设备列表', res);
			state.isMore = res.data.is_more;
			if (state.list.length == 0) {
				state.list = res.data.list;
			} else {
				state.list = state.list.concat(res.data.list);
			}
		})
	}

	function getSearchCriteria() {
		request.get("filters.equipment/getSelectData", state.params).then(res => {
			console.log('选择数据', res);
			deviceTypeList.value = res.data.deviceTypeList;
			deviceModelList.value = res.data.deviceModelList;

			let holder_type_list = res.data.holderTypeList;
			holder_type_list.forEach(item => {
				if (item.value == 3 || item.value == 4) {
					holderTypeList.value.push(item);
				}
			})

			let sales_method_list = res.data.salesMethodList;
			sales_method_list.forEach(item => {
				if (item.value != -1) {
					salesMethodList.value.push(item);
				}
			})
		})
	}

	function search() {
		state.isMore = true;
		state.list = [];
		getDataList();
	}

	function changeTab(type) {
		state.params.current = type;
		search();
	}

	function changeDeviceType(e) {
		console.log('设备类型', e);
		state.params.device_type = e;
		search();
	}

	function changeDeviceModel(e) {
		console.log('设备型号', e);
		state.params.device_model = e;
		search();
	}

	function changeHolderType(e) {
		console.log('持有人类型', e);
		state.params.holder_type = e;
		search();
	}

	function changeSalesMethod(e) {
		console.log('销售方式', e);
		state.params.sales_method = e;
		search();
	}

	function getProvince() {
		request.get('address/getAreaByPid', {
			pid: 0
		}).then(res => {
			provinceList.value = res.data;
			provinceList.value.forEach(item => {
				item.text = item.label; // 添加 text 属性
				delete item.label; // 删除 label 属性
			})
		})
	}

	function getCity() {
		if (!state.params.province) {
			return
		}
		request.get('address/getAreaByPid', {
			pid: state.params.province
		}).then(res => {
			cityList.value = res.data
			cityList.value.forEach(item => {
				item.text = item.label; // 添加 text 属性
				delete item.label; // 删除 label 属性
			})
			search();
		})
	}

	function getArea() {
		if (!state.params.city) {
			return
		}
		request.get('address/getAreaByPid', {
			pid: state.params.city
		}).then(res => {
			areaList.value = res.data
			areaList.value.forEach(item => {
				item.text = item.label; // 添加 text 属性
				delete item.label; // 删除 label 属性
			})
			search();
		})
	}

	function batchOperation() {
		state.operate = !state.operate;
		if (!state.operate) {
			state.selectIds = [];
		}
	}

	function allocate(item) {
		state.selectIds = [item.id];
		console.log('划拨设备id', state.selectIds);
		uni.showModal({
			title: '温馨提示',
			content: '设备一旦划拨成功后，将不再支持改价，确定要继续划拨吗？',
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
					allocateRef.value.open();
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	function adjustment(item) {
		state.selectIds = [item.id];
		console.log('改价设备id', state.selectIds);
		// adjustmentRef.value.open();
		uni.$emit('selDeviceIds', state.selectIds);
		pageRoute('/agentPages/equipment-manage/price-adjustment?selDeviceIds=' + JSON.stringify(state.selectIds));
	}

	function checkboxChange(e) {
		console.log('选择', e, state.selectIds);
	}

	function batchAllocate() {
		console.log('批量划拨设备id', state.selectIds);
		if (state.selectIds.length == 0) {
			util.showTip('请先选择需要操作设备');
			return;
		}
		uni.showModal({
			title: '温馨提示',
			content: '设备一旦划拨成功后，将不再支持改价，确定要继续划拨吗？',
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
					allocateRef.value.open();
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	function batchAdjustment() {
		console.log('批量改价设备id', state.selectIds);
		if (state.selectIds.length == 0) {
			util.showTip('请先选择需要操作设备');
			return;
		}
		// adjustmentRef.value.open();
		uni.$emit('selDeviceIds', state.selectIds);
		pageRoute('/agentPages/equipment-manage/price-adjustment?selDeviceIds=' + JSON.stringify(state.selectIds));
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		dataInfo,
		params,
		isMore,
		list,
		operate,
		selectIds,
	} = toRefs(state);
</script>

<style lang="scss">
	page {
		background: linear-gradient(180deg, #eff6ff 0%, #f7f7fb 54%);
	}

	.equipment-manage {
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));

		.content {
			padding: $m24;

			.statistics-card {
				display: flex;
				flex-wrap: wrap;
				padding: 12rpx;
				background-color: #fff;
				border-radius: $radius-16;
				text-align: center;

				.grid-item {
					display: flex;
					flex-direction: column;
					flex: 1;

					.label {
						font-size: $font-28;
					}

					.value {
						font-size: $font-36;
						color: $primary-color;
						font-weight: 500;
					}
				}

				.active {
					.label {
						color: $primary-color;
					}
				}
			}

			.status-box {
				padding: $m24 0;
			}

			.filter-box {
				display: flex;
				align-items: center;
				padding: $m24 0;

				.filter-item {
					@include f-center;
					margin-right: $m20;
					padding: .1em .1em;
					background-color: #fff;
					border-radius: $radius-8;
					width: 200rpx;

					.label {
						margin-right: 10rpx;
					}
				}

				.area-opt {
					display: flex;
					width: auto;

					.area-item {
						@include f-center;
						margin-right: $m20;
						padding: .2em .6em;
						background-color: #fff;
						border-radius: $radius-8;
						width: 210rpx;
					}
				}
			}

			.device-card {
				width: 100%;
				margin-bottom: $m24;
				padding: 0 $m24;
				background-color: #fff;
				border-radius: $radius-16;

				&:last-child {
					margin-bottom: 0;
				}

				.device-info {
					display: flex;

					.checkbox {
						width: 50rpx;
					}

					.info-left {
						flex: 1;

						.value {
							text {
								margin-left: 10rpx;
							}
						}
					}

					.info-right {
						width: 80rpx;
						padding: 10rpx;

						.btn-group {
							display: block;

							.btn {
								margin-top: 10rpx;
							}
						}
					}
				}
			}
		}

		.footer {
			position: fixed;
			/* 固定在底部 */
			bottom: 0;
			width: 100%;

			.btn-group {
				display: flex;

				.btn {
					width: 200rpx;
				}
			}
		}
	}
</style>